package com.bxd.baodan.list;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.widget.AbsListView;

import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.App;
import com.bxd.baodan.activity.InsuranceActivity;
import com.bxd.baodan.activity.QuestionDetailActivity;
import com.bxd.baodan.activity.VideoDetailActivity;
import com.bxd.baodan.activity.WebViewPager;
import com.bxd.baodan.adapter.AnswerMessageAdapter;
import com.bxd.baodan.adapter.MessageAdapter;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.base.BaseDBListFragment;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.interfaces.OnDataLoadCompleteListener;
import com.bxd.baodan.item.MessageItem;
import com.bxd.baodan.util.StringUtil;
import com.umeng.analytics.MobclickAgent;

import java.sql.SQLException;
import java.util.List;

public class MessageListFragment extends BaseDBListFragment implements
        OnDataLoadCompleteListener {
    private ReceiveBroadCast receiveBroadCast;
    private String[] type;

    public static Fragment newInstance(String[] type) {
        MessageListFragment fragment = new MessageListFragment();
        fragment.type = type;
        return fragment;
    }

    /**
     * 清除msg时候调用
     */
    public void clearAllNotifications() {
        for (int i = 0; i < adapter.getCount(); i++) {
            MessageItem item = (MessageItem) adapter.getItem(i);
            cleanNotificationByMessageItemId(item);
        }
        ((MessageAdapter) adapter).clear();
    }

    // TODO: 17/7/23 退出登录时,清理数据库

    public void cleanNotificationByMessageItemId(MessageItem item) {
        NotificationManager mNotificationManager = (NotificationManager) this
                .getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(item.getId());
    }

    public void clearAllNot() {
        for (int i = 0; i < adapter.getCount(); i++) {
            MessageItem item = (MessageItem) adapter.getItem(i);
            cleanNotificationByTag(item.getQid() + "_" + item.getAid(),
                    item.getQid());
        }
        ((MessageAdapter) adapter).clear();
    }

    public void cleanNotificationByTag(String tag, int qid) {
        NotificationManager mNotificationManager = (NotificationManager) this
                .getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(tag, qid);
    }

    @Override
    public void setEmptyString() {
        emptyText = "这里面空荡荡的，一条消息都没有！";
    }

    @Override
    public void onItemClick(int position) {
        MobclickAgent.onEvent(App.getContext(), "v6_0_0_WD_xxzx_dt_xq");
        MessageItem item = (MessageItem) adapter.getItem(position);
        //活动与阅读
        if (item.getType() == Constant.MSG_NEW_ACTIVITIES || item.getType() == Constant.MSG_NEW_READ) {
            if (item.getUrl() != null && !item.getUrl().equals("")) {
                Intent intent = new Intent(getActivity(), WebViewPager.class);
                intent.putExtra("startUrl", item.getUrl());
                startActivity(intent);
            }
        }
        //聊天
        else if (item.getQid() != -1 && item.getType() == Constant.MSG_NEW_ANSWER) {
            MobclickAgent.onEvent(App.getContext(), "v5_5_1_XX_wd_wt");
            Intent intent = new Intent(this.getActivity(), QuestionDetailActivity.class);
            intent.putExtra("qid", item.getQid() + "");
            startActivity(intent);
        }
        //小视频
        else if (item.getQid() != -1 && item.getType() == Constant.MSG_NEW_VIDEO) {
            Intent intent = new Intent(this.getActivity(), VideoDetailActivity.class);
            intent.putExtra("video_id", item.getA_id());
            startActivity(intent);
        } else if (!StringUtil.isEmpty(item.getBdId()) && item.getType() == Constant.MSG_NEW_BAODAN) {
            openActivity(InsuranceActivity.class, new String[]{"params"}, new String[]{item.getBdId()});
        }

        //设置消息已读
        setIsNoReadDateID(item);
    }

    public int setIsNoReadDateID(MessageItem item) {
        Dao<MessageItem, ?> dao;
        int is = 0;
        try {
            dao = DBHelper.getInstance(getActivity()).getDao(MessageItem.class);
            item.setIsread(true);
            dao.createOrUpdate(item);
            setNotift();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return is;
    }

    public void allRead() {


        try {
            Dao<MessageItem, ?> dao = DBHelper.getInstance(getActivity()).getDao(MessageItem.class);
            List<MessageItem> list;
            if (type[0].equals("0")) {
                list = dao.queryBuilder().where().
                        eq("uid", LoginInfo.getInstance(context).getUser().getU_id()).and().
                        eq("isread", false).and().in("type", type)
                        .query();
            } else {
                list = dao.queryBuilder().where().
                        eq("isread", false).and().in("type", type)
                        .query();
            }

            if (list != null && list.size() > 0) {

                for (MessageItem item : list) {
                    item.setIsread(true);
                    dao.createOrUpdate(item);
                }
            }

            for (int i = 0; i < adapter.getCount(); i++) {
                MessageItem item = (MessageItem) adapter.getItem(i);
                item.setIsread(true);
            }
            setNotift();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void setNotift() {
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // setIsNoReadDateType();
        // 广播接收器
        initReceivers();
    }


    private void initReceivers() {

        if (receiveBroadCast == null) {

            receiveBroadCast = new ReceiveBroadCast();
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.ACTION_RECEIVE_AD);
            this.getActivity().registerReceiver(receiveBroadCast, filter);
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    class ReceiveBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (Constant.ACTION_RECEIVE_AD.equals(arg1.getAction())) {
                freshMsgCount();
            }
        }

    }

    public void freshMsgCount() {
        for (int i = 0; i < adapter.getCount(); i++) {
            MessageItem item = (MessageItem) adapter.getItem(i);
            item.setNoReadCount(DBHelper.getInstance(getActivity())
                    .getNoReadCount(item));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void initAdapter() {
        if (type != null) { // FIXME: 2017/7/4 需要解决type为空时遗留的问题
            if (type[0].equals("0")) {
                adapter = new AnswerMessageAdapter(getActivity(), type);
            } else {
                adapter = new MessageAdapter(getActivity(), type);
            }
            getListView().setDividerHeight(0);
            adapter.setOnDbDataFreshedListener(this);
        }
    }

    @Override
    public void onDbDataFreshed() {
        super.refreshComplete();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiveBroadCast);
        receiveBroadCast = null;
    }
}
